//
//  EmojiButtonView.m
//  KeyBoard
//
//  Created by ShaoFeng on 16/8/18.
//  Copyright © 2016年 Cocav. All rights reserved.
//
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define CustomBackGroundColor [UIColor colorWithRed:243 / 255.0 green:243 / 255.0 blue:243 / 255.0 alpha:1]
#define EMOJI_CODE_TO_SYMBOL(x) ((((0x808080F0 | (x & 0x3F000) >> 4) | (x & 0xFC0) << 10) | (x & 0x1C0000) << 18) | (x & 0x3F) << 24);

// 一行中 cell的个数
#define ItemCountPerRow 7
// 一页显示多少行
#define RowCount 3
//每页的个数
#define PageCount (ItemCountPerRow * RowCount)

//本地表情的种类
#define LocalEmoticonTypeCount 2

#import "EmojiButtonView.h"
#import "CollectionViewFlowLayout.h"
#import "EmojiCollectionViewCell.h"
#import "UIView+Category.h"
#import "EmotionImages.h"

@interface EmojiButtonView ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic,strong)CollectionViewFlowLayout *layout;
@property (nonatomic,strong)UICollectionView *collectionView;

@property (nonatomic,strong)UIPageControl *pageControl;

@property (nonatomic,strong)UIView *emojiFooterView;
@property (nonatomic,strong)UIScrollView *emojiFooterScrollView;

@property (nonatomic,strong)UIButton *sendButton;

@property (nonatomic,strong)UIButton *emojiButotn;
@property (nonatomic,strong)UIButton *emojiImageButotn;

@property (nonatomic,strong)NSMutableArray *emojiEmoticons;
@property (nonatomic,strong)NSMutableArray *emoticonImages;

@property (nonatomic,strong)NSMutableArray *totalEmoticons;

@property (nonatomic,strong)NSMutableArray *subButtons;

@end

@implementation EmojiButtonView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
         self.backgroundColor = CustomBackGroundColor;
        
        //初始化数组
        _emojiEmoticons = [NSMutableArray array];
        _totalEmoticons = [NSMutableArray array];
        
        _emoticonImages = [NSMutableArray array];
        
        _subButtons = [NSMutableArray array];
        
        //-----获取字符表情-------
        for (int i=0x1F600; i<=0x1F64F; i++)
        {
            if (i < 0x1F641 || i > 0x1F640) {
                int sym = EMOJI_CODE_TO_SYMBOL(i);
                NSString *emoT = [[NSString alloc] initWithBytes:&sym length:sizeof(sym) encoding:NSUTF8StringEncoding];
                [_emojiEmoticons addObject:emoT];
            }
        }
        //为布局修改数据源
        _emojiEmoticons = [self fixEmoticonsToWholePage:_emojiEmoticons];
        
        //总数据源
        _totalEmoticons = [NSMutableArray arrayWithArray:_emojiEmoticons];
        
        //-----表情图数据源-------
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            [[EmotionImages shareEmotinImages] initEmotionImages];
            //获取表情图片
            weakSelf.emoticonImages = [EmotionImages shareEmotinImages].images;
            //为布局修改数据源
            weakSelf.emoticonImages = [weakSelf fixEmoticonsToWholePage:weakSelf.emoticonImages];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.totalEmoticons addObjectsFromArray:weakSelf.emoticonImages];
                [weakSelf.collectionView reloadData];
            });
            
        });
        
        [self layoutUI];
        
    }
    return self;
}

- (NSMutableArray *)fixEmoticonsToWholePage:(NSMutableArray *)emoticons
{
    //分页的末尾插入删除按钮
    for (NSInteger i = 0;i < emoticons.count;i ++)
    {
        if (i != 0 && i % PageCount == 0)
        {
            NSLog(@"----------：%ld",i-1);
            [emoticons insertObject:deleteButtonId atIndex:i-1];
        }
    }
    
    //剩下不够一整页的
    if (emoticons.count % PageCount != 0)
    {
        NSLog(@"~~~~~~~：%lu",emoticons.count % PageCount);
        
        for (NSInteger i = emoticons.count; i < emoticons.count + PageCount; i ++)
        {
            [emoticons addObject:@""];
            //填满了一整页，跳出循环
            if (emoticons.count % PageCount == 0) {
                break;
            }
        }
    }
    
    //末尾加入删除按钮
    [emoticons replaceObjectAtIndex:emoticons.count - 1 withObject:deleteButtonId];
    
    NSLog(@"---------%@",emoticons);
    
    return emoticons;
}

- (void)layoutUI
{
    //collectionView
    self.layout = [[CollectionViewFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 130) collectionViewLayout:self.layout];
    CGFloat W = (self.collectionView.bounds.size.width) / ItemCountPerRow;
    CGFloat H = (self.collectionView.bounds.size.height) / RowCount;
    self.layout.itemSize = CGSizeMake(W, H);
    CGFloat insetY = (self.collectionView.bounds.size.height - 3 * H);
    self.collectionView.contentInset = UIEdgeInsetsMake(insetY, 0, 0, 0);
    self.collectionView.backgroundColor = CustomBackGroundColor;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self addSubview:self.collectionView];
    
    [self.collectionView registerClass:[EmojiCollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    
    //pageControl
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.collectionView.bottom + 10, 0, 10)];
    self.pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
    self.pageControl.pageIndicatorTintColor = [UIColor grayColor];
    self.pageControl.userInteractionEnabled = NO;
    self.pageControl.numberOfPages = self.emojiEmoticons.count / PageCount;
    [self addSubview:self.pageControl];
    
    //底部操作条
    self.emojiFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, self.pageControl.bottom + 10, SCREEN_WIDTH, 40)];
    self.emojiFooterView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.emojiFooterView];
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
    line.backgroundColor = [UIColor lightGrayColor];
    [self.emojiFooterView addSubview:line];
    
    self.sendButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 5 * 4, 0.5, SCREEN_WIDTH / 5, self.emojiFooterView.height - 0.5)];
    [self.sendButton setTitle:@"发送" forState:UIControlStateNormal];
    self.sendButton.backgroundColor = [UIColor colorWithRed:230 / 255.0 green:230 / 255.0 blue:230 / 255.0 alpha:1];
    self.sendButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.sendButton setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];
    [self.sendButton addTarget:self action:@selector(clickSenderButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.emojiFooterView addSubview:self.sendButton];
    
    //底部ScrollView布局
    self.emojiFooterScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - (self.sendButton.width) - 1, self.emojiFooterView.height)];
//    self.emojiFooterScrollView.backgroundColor = [UIColor cyanColor];
    self.emojiFooterScrollView.showsHorizontalScrollIndicator = NO;
    self.emojiFooterScrollView.showsVerticalScrollIndicator = NO;
    [self.emojiFooterView addSubview:self.emojiFooterScrollView];
    
    //scrollView表情切换按钮
    CGFloat buttonH = self.emojiFooterView.height;
    CGFloat buttonW = buttonH;
    CGFloat space = 20;
    for (int i = 0; i < LocalEmoticonTypeCount ; i++)
    {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake((buttonW + space) * i + space, 0, buttonW, buttonH);
        [button setImage:[UIImage imageNamed:@"liaotian_ic_biaoqing_nor"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"liaotian_ic_biaoqing_press"] forState:UIControlStateSelected];
        button.tag = i + 1;
        [button addTarget:self action:@selector(clickEmojiButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.emojiFooterScrollView addSubview:button];
        if (i == 0) button.selected = YES;
        
    }
    
    //设置偏移量
     self.emojiFooterScrollView.contentSize = CGSizeMake((buttonW + space) * LocalEmoticonTypeCount + space, self.emojiFooterView.height);
    
    
}

//选中哪个表情组
- (void)selectedEmotionBtn:(NSInteger)currentTag
{
    for (int i = 0; i < self.emojiFooterScrollView.subviews.count; i++)
    {
        UIButton *currentBtn = self.emojiFooterScrollView.subviews[i];
        if (currentBtn.tag == currentTag) {
            currentBtn.selected = YES;
        } else {
            currentBtn.selected = NO;
        }
    }
}

#pragma mark -- UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.collectionView)
    {
        //字符表情页长度
        CGFloat emojiTotalW = SCREEN_WIDTH * (self.emojiEmoticons.count / PageCount);
        //图片表情页长度
        CGFloat emoticonImageTotalW = emojiTotalW + (SCREEN_WIDTH * (self.emoticonImages.count / PageCount));
        
        NSLog(@"_____:%f",scrollView.contentOffset.x);
        
        if (scrollView.contentOffset.x < emojiTotalW)
        {
            self.pageControl.numberOfPages = self.emojiEmoticons.count / PageCount;
            self.pageControl.currentPage = (scrollView.contentOffset.x / SCREEN_WIDTH);

            [self selectedEmotionBtn:1];
            
        } else if (scrollView.contentOffset.x >= emojiTotalW && scrollView.contentOffset.x < emoticonImageTotalW)
        {
            self.pageControl.numberOfPages = self.emoticonImages.count / PageCount;
            self.pageControl.currentPage = ((scrollView.contentOffset.x - SCREEN_WIDTH * (self.emojiEmoticons.count / PageCount)) / SCREEN_WIDTH);
            
            [self selectedEmotionBtn:2];
            
        } else {
            
        }
    }
}


#pragma mark -- UICollectionViewDataSource,UICollectionViewDelegate

- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.totalEmoticons.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    EmojiCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
    if ([self.totalEmoticons[indexPath.row] isKindOfClass:[UIImage class]]) {
        cell.image = self.totalEmoticons[indexPath.row];
    } else {
        cell.string = self.totalEmoticons[indexPath.row];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSObject *str = self.totalEmoticons[indexPath.row];
    if (str) {
        if ([_delegate respondsToSelector:@selector(emojiButtonView:emojiText:)]) {
            [_delegate emojiButtonView:self emojiText:str];
        }
    }
}

#pragma mark -- 表情组点击
- (void)clickEmojiButton:(UIButton *)button
{
    [self selectedEmotionBtn:button.tag];
    
    CGFloat emojiPages = self.emojiEmoticons.count / PageCount;
    CGFloat emotionImgPages = self.emoticonImages.count / PageCount;
    
    //默认
    CGPoint point = CGPointMake(0, 0);
    NSInteger numberOfPages = emojiPages;
    NSInteger currentPage = 0;
    
    if (button.tag == 1) {
        //默认
    } else if (button.tag == 2)
    {
        point = CGPointMake(SCREEN_WIDTH * emojiPages,0);
        numberOfPages = emotionImgPages;
        currentPage = ((self.collectionView.contentOffset.x - SCREEN_WIDTH * emojiPages) / SCREEN_WIDTH);
    }
    
    [self.collectionView setContentOffset:point animated:0];
    self.pageControl.numberOfPages = numberOfPages;
    self.pageControl.currentPage = currentPage;
}

#pragma mark -- 点击了发动按钮
- (void)clickSenderButton:(UIButton *)sender
{
    if ([_delegate respondsToSelector:@selector(emojiButtonView:sendButtonClick:)]) {
        [_delegate emojiButtonView:self sendButtonClick:sender];
    }
}

@end
